import { useState, useRef } from "react";
import { isFunction } from "lodash";
import { useUpdateEffect } from "ahooks";

const useSetState = (initState?: any) => {
	const [state, setState] = useState(initState);
	const isUpdate = useRef<any>(null);
	const setXState = (newState: any, callback: (s: any) => void) => {
		isUpdate.current = callback;
		setState(newState);
	};

	useUpdateEffect(() => {
		if (isUpdate.current && isFunction(isUpdate.current)) {
			isUpdate.current(state);

			setTimeout(() => {
				isUpdate.current = null;
			}, 10);
		}
	}, [state]);

	return [state, setXState];
};

export default useSetState;
